package com.industrial.operation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.core.web.page.TableDataInfo;
import com.industrial.common.security.annotation.RequiresPermissions;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.operation.domain.SysDataReportingScoreAppeal;
import com.industrial.operation.domain.SysDataReportingScoreAppealFile;
import com.industrial.operation.mapper.SysDataReportingScoreAppealFileMapper;
import com.industrial.operation.mapper.SysDataReportingScoreAppealMapper;
import com.industrial.operation.service.ISysDataReportingScoreAppealService;
import com.industrial.system.api.domain.SysUser;
import com.industrial.system.api.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SysDataReportingScoreAppealServiceImpl implements ISysDataReportingScoreAppealService {

    @Autowired
    private SysDataReportingScoreAppealMapper sysDataReportingScoreAppealMapper;

    @Autowired
    private SysDataReportingScoreAppealFileMapper sysDataReportingScoreAppealFileMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private Set<String> zbSet = new HashSet<>();

    private Map<String,String> result = new HashMap<String,String>();

    @PostConstruct
    public void init(){
        zbSet.add("perMuGdp");
        zbSet.add("preMuAla");
        zbSet.add("preMuEcPt");
        zbSet.add("preMuEcTec");
        zbSet.add("lpvGdp");
        zbSet.add("lpvAvNumEmploy");
        zbSet.add("epResearchDevelop");
        zbSet.add("epOperatingRevenue");
        zbSet.add("pollutionEmission");
        zbSet.add("pollutionGdp");
        zbSet.add("compDevelopMvg");
        zbSet.add("compDevelopQr");
        zbSet.add("compDevelopEn");
        zbSet.add("compDevelopRc");
        zbSet.add("compDevelopTo");
        zbSet.add("compDevelopProduc");
        zbSet.add("innovLeadRdOr");
        zbSet.add("innovLeadIp");
        zbSet.add("innovLeadIs");
        zbSet.add("yytj");
        result.put("perMuGdp","全部工业增加值");
        result.put("preMuAla","规模以上工业增加值增速");
        result.put("preMuEcPt","制造业增值税、企业所得税等重点税收贡献情况");
        result.put("preMuEcTec","制造业增加值占 CDP 比重及提高幅度");
        result.put("lpvGdp","规模以上工业企业数量及增幅");
        result.put("lpvAvNumEmploy","工业投资增速");
        result.put("epResearchDevelop","工业技术改造投资增速");
        result.put("epOperatingRevenue","规模以上工业企业亩均税收");
        result.put("pollutionEmission","省级以上专精特新和单项冠军数量");
        result.put("pollutionGdp","能源原材料工业占规上工业增加值比重");
        result.put("compDevelopMvg","制造业贷款占各项贷款余额比重");
        result.put("compDevelopQr","规模以上工业企业 R&D 经费支出占营业收入比重");
        result.put("compDevelopEn","高技术产业产值占规模以上工业总产值比重");
        result.put("compDevelopRc","数字经济核心产业收入规模");
        result.put("compDevelopTo","规模以上工业企业新产品销售收入占规模以上工业营业收入比重");
        result.put("compDevelopProduc","规模以上工业单位增加值能耗降低率");
        result.put("innovLeadRdOr","PM2.5 平均浓度及同比改善率");
        result.put("innovLeadIp","省级以上绿色工业园区、工厂和供应链数量");
        result.put("innovLeadIs","绿色贷款余额占各项贷款余额比重");
        result.put("yytj","是否发生重大及以上生产安全责任事故、重大产品质量事件、重大及以上突发环境事件、统计数据不实问题");
    }

    /**
     * 查询申诉数据的列表
     *
     * @param sysDataReportingScoreAppeal
     * @return
     */
    @Override
    public List<SysDataReportingScoreAppeal> selectSysDataReportingScoreAppealList(SysDataReportingScoreAppeal sysDataReportingScoreAppeal) {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        Set<String> roles = loginUser.getRoles();

        SysUser sysUser = loginUser.getSysUser();
        if(sysUser == null){
            throw new RuntimeException("没有找到用户信息");
        }

        //省级
        if(roles.contains("p_01_011")){
            sysDataReportingScoreAppeal.setProvince(sysUser.getProvince());
        }else if(roles.contains("x_01_011")){
            sysDataReportingScoreAppeal.setProvince(sysUser.getProvince());
            sysDataReportingScoreAppeal.setCity(sysUser.getCity());
            sysDataReportingScoreAppeal.setDistrict(sysUser.getDistrict());
        }
//        else{
//            throw new RuntimeException("您当前没有查看的权限");
//        }


        List<SysDataReportingScoreAppeal> result = sysDataReportingScoreAppealMapper.selectSysDataReportingScoreAppealList(sysDataReportingScoreAppeal);
        for(SysDataReportingScoreAppeal item : result){
            String province = item.getProvince();
            String city = item.getCity();
            String district = item.getDistrict();

            StringBuilder addressStr = new StringBuilder();
            if(StringUtils.isNotBlank(province)){
                addressStr.append(stringRedisTemplate.opsForValue().get("area:" + province));
            }
            if(StringUtils.isNotBlank(city)){
                addressStr.append("-").append(stringRedisTemplate.opsForValue().get("area:" + city));
            }
            if(StringUtils.isNotBlank(district)){
                addressStr.append("-").append(stringRedisTemplate.opsForValue().get("area:" + district));
            }
            item.setAddress(addressStr.toString());
        }
        return result;
    }

    /**
     * 查看申诉详情
     *
     * @param baseId
     * @return
     */
    @Override
    public AjaxResult getScoreAppeaInfoByBaseId(String baseId) {
        SysDataReportingScoreAppeal sysDataReportingScoreAppeal = sysDataReportingScoreAppealMapper.getScoreAppeaInfoByBaseId(baseId);
        if(Objects.isNull(sysDataReportingScoreAppeal)){
            return AjaxResult.success(new ArrayList<SysDataReportingScoreAppeal>());
        }
        Map<String, Object> sysDataReportingScoreAppealMap = BeanUtil.beanToMap(sysDataReportingScoreAppeal);
        List<Map<String,Object>> resultList = new ArrayList<>();

        String appealBaseId = sysDataReportingScoreAppeal.getBaseId();
        List<SysDataReportingScoreAppealFile> reportingScoreAppealFiles = sysDataReportingScoreAppealFileMapper.selectSysDataReportingScoreAppealFileByPkId(appealBaseId);
        Map<String, String> fileMap = new HashMap<>(16);
        if(reportingScoreAppealFiles != null && !reportingScoreAppealFiles.isEmpty()){
            fileMap = reportingScoreAppealFiles.stream().collect(Collectors.toMap(SysDataReportingScoreAppealFile::getIndexCode, SysDataReportingScoreAppealFile::getFilePath));
        }


        for(Map.Entry<String,Object> item : sysDataReportingScoreAppealMap.entrySet()){
            Object value = item.getValue();
            if(!Objects.isNull(value) && zbSet.contains(item.getKey())){
                Map<String,Object> resultMap = new HashMap<>(16);
                resultMap.put("currentScore",value);
                resultMap.put("zbName",result.get(item.getKey()));
                resultMap.put("zbCode",item.getKey());
                resultMap.put("pkId",sysDataReportingScoreAppeal.getPkId());
                resultMap.put("baseId",sysDataReportingScoreAppeal.getBaseId());
                resultMap.put("appealDesc",sysDataReportingScoreAppealMap.get(item.getKey() + "Appeal"));
                if(fileMap.containsKey(item.getKey())){
                    resultMap.put("file",fileMap.get(item.getKey()));
                }
                resultList.add(resultMap);
            }
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("list",resultList);
        resultMap.put("yy",sysDataReportingScoreAppeal.getRejection());
        return AjaxResult.success(resultMap);
    }

    /**
     * 审核申诉
     *
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult checkScoreAppea(SysDataReportingScoreAppeal params) {
        String baseId = params.getBaseId();
        String checkStatus = params.getCheckStatus();
        if(StringUtils.isBlank(baseId) || StringUtils.isBlank(checkStatus)){
            return AjaxResult.warn("没有找到要修改的数据主键或都状态");
        }
        sysDataReportingScoreAppealMapper.updateSysDataReportingScoreAppeal(params);
        return AjaxResult.success("审核成功");
    }
}
